const express = require('express')
const User = require('../../model/user')
    // const Chat = require('../../model/chat')
const Public = require('../../model/publicmsg')
const Private = require('../../model/privatemsg')
var router = express.Router();
//获取注册用户
router.get('/allusers', (req, res, next) => {
    User.find().then(users => {
        let AllUsers = []
        users.forEach(e => {
                let user = {
                    _id: e._id,
                    username: e.username,
                    nickname: e.nickname,
                    avatar: e.avatar
                }
                AllUsers.push(user)
            })
            // console.log(AllUsers)
        res.send(AllUsers)
    })
});
//获取数据库群聊的信息
router.get('/getpublic', (req, res, next) => {
    Public.find().populate('user').then(data => {
        console.log(data)
        let message = []
        data.forEach(e => {
            let msg = {
                send_id: e.user._id,
                nickname: e.user.nickname,
                username: e.user.username,
                avatar: e.user.avatar,
                msg: e.message
            }
            message.push(msg)
        })
        res.send(message)
    })
});
//获取数据库与好友的聊天信息
router.post('/getprivate', (req, res, next) => {
    console.log(req.body)
    let send_id = req.body.send_id;
    let receive_id = req.body.receive_id;
    Private.find({
        $or: [{
                $and: [
                    { sendUser: send_id },
                    { receiveUser: receive_id }
                ],
            },
            {
                $and: [
                    { sendUser: receive_id },
                    { receiveUser: send_id }
                ]
            }
        ]
    }).populate('sendUser').then(result => {
        let data = []
        result.forEach(e => {
            let obj = {
                _id: e._id,
                send_id: e.sendUser._id,
                receive_id: e.receiveUser,
                avatar: e.sendUser.avatar,
                nickname: e.sendUser.nickname,
                msg: e.msg,
                date: e.date
            }
            data.push(obj)
        })
        console.log(data)
        res.send(data)
    })

})
module.exports = router;